package main

import (
	"bytes"
	"context"
	"errors"
	"github.com/SkyAPM/go2sky/propagation"
	"github.com/gin-gonic/gin"
	"io/ioutil"
	"net/http"
	"time"
	"gitee.com/zhucheer/tracing/sw"
)

func main() {

	// [必要步骤1]初始化skywalking 配置服务端信息
	sw.InitSkyWalking("0.0.0.0:11800", "xxx","testTraceGin")

	// 应用结束后关闭连接
	defer sw.CloseReport()

	router := gin.Default()

	// [必要步骤2]加载中间件
	router.Use(sw.EntrySpan(router))

	router.GET("/someGet", func(c *gin.Context) {

		traceId, _ := c.Get(sw.SWTraceId)
		postJson(c, "http://127.0.0.1:8088/v1/sim/unbind/notify/89860619100011923390", []byte(""), 3)

		c.JSON(200, gin.H{
			"message": "pong",
			"traceId": traceId,
		})
	})

	router.Run(":8012")

}

// 对外发起 http 请求
func postJson(c *gin.Context, url string, data []byte, timeout uint32) ([]byte, error) {
	var defaultClient = &http.Client{
		Transport: &http.Transport{
			MaxIdleConnsPerHost: 100,
		},
	}

	req, err := http.NewRequest("POST", url, bytes.NewBuffer(data))
	if err != nil {
		return nil, err
	}

	// 超时设置
	ctx, cancel := context.WithTimeout(context.Background(), time.Duration(timeout)*time.Second)
	defer cancel()

	// [必要步骤3] 创建exitSpan
	exitSpan := sw.ExitSpanRequestDo(c, url, "post", url)
	defer exitSpan.End()

	// 无论使用何种方式进行http调用，在请求头中加上skywalking信息即可
	req.Header.Add(propagation.Header, c.Request.Header.Get(propagation.Header))
	req.Header.Add("Content-Type", "application/json;charset=utf-8")

	req = req.WithContext(ctx)

	resp, err := defaultClient.Do(req)
	if err != nil {
		return nil, err
	}

	defer resp.Body.Close()

	if resp.StatusCode != 200 {
		// 如果接口报错则标记错误信息
		exitSpan.Error(time.Now(), "error message")

		return nil, errors.New("HTTP " + resp.Status)
	}

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}

	return body, nil
}
